﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace DAL
{
    public class Database
    {
        public static SouthWindEntities GetContext()
        {
            return new SouthWindEntities();
        }
        public static T Find<T>(params object[] keyValues) where T : class
        {
            try
            {
                using (var context = GetContext())
                {
                    return context.Set<T>().Find(keyValues);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return null;
        }

        public static Boolean Insert<T>(T bean) where T : class
        {
            try
            {
                using (var context = GetContext())
                {
                    context.Set<T>().Add(bean);
                    context.SaveChanges();
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return false;
        }

        public static Boolean Delete<T>(T bean) where T : class
        {
            try
            {
                using (var context = GetContext())
                {
                    context.Set<T>().Remove(bean);
                    context.SaveChanges();
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return false;
        }

        public static Boolean Update<T>(T bean) where T : class
        {
            try
            {
                using (var context = GetContext())
                {
                    if (!context.Set<T>().Contains(bean))
                    {
                        context.Set<T>().Add(bean);
                    }
                    context.Entry(bean).State = EntityState.Modified;
                    context.SaveChanges();
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return false;
        }
    }
}